package qs.openxt.libs.plugins;

import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import qs.openxt.libs.R;
import qs.openxt.libs.file.FileSelectorActivity;
import qs.openxt.libs.fragment.ConfirmDialogListener;
import qs.openxt.libs.progress.Wait;
import qs.openxt.libs.remoting.Upload;
import qs.openxt.libs.remoting.Upload.OnActionListener;
import qs.openxt.libs.util.ActivityUtil;
import qs.openxt.libs.util.JSONUtil;
import qs.openxt.libs.util.PictureUtil;
import qs.openxt.libs.util.StringUtil;

/**
 * 文件上传
 * @author 颖杰_2
 *
 */
public class FileUploadPlugins extends CordovaPlugin{
	private CallbackContext callbackContext;
	public static final int RETURNTYPE_FILEUPLOAD = 1;
	private String url = null;
	private Object data = null;
	private String type = null;
    private boolean showConfirm = true;
	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
				case 1:{
					try {
						List<String> list = (List<String>)msg.obj;
						if(list == null || list.isEmpty())
							break;
                        com.alibaba.fastjson.JSONObject params = new com.alibaba.fastjson.JSONObject();
						params.put("file", list);
						params.put("url", url);
						Object val = data;
						if (val != null) {
							if (val instanceof JSONObject) {
								params.put("param", JSONUtil.toJSON((JSONObject) val));
							} else if (!StringUtil.isNull(val)) {
								String[] split = val.toString().split("\\&");
								if (split.length > 1) {
									JSONObject param = new JSONObject();
									for (int i = 0; i < split.length; i++) {
										String[] $split = split[i].split("\\=");
										if ($split.length == 2)
											param.put($split[0], $split[1]);
									}
									params.put("param", param);
								}
							}
						}

						Upload upload = new Upload(cordova.getActivity(), new OnActionListener() {
							@Override
							public void onActionCompleted(final String reVal) {
								Message message = new Message();
								message.what = 2;
								message.obj = reVal;
								mHandler.sendMessage(message);
							}

							@Override
							public void onActionError() {
								Message message = new Message();
								message.what = 3;
								mHandler.sendMessage(message);
							}
						});
						upload.doRequest(params);
					} catch (Exception e) {
					}
					break;
				}
				case 2:{
					callbackContext.success((String)msg.obj);
					break;
				}
				case 3:{
					Toast.makeText(cordova.getActivity(), "文件上传失败", Toast.LENGTH_SHORT).show();
					break;
				}
                case 4:{
                    Toast.makeText(cordova.getActivity(), (String)msg.obj, Toast.LENGTH_SHORT).show();
                    break;
                }
			default:
				break;
			}
		};
	};
	
	public boolean execute(String action, final JSONArray args, final CallbackContext callbackContext) throws JSONException {
		this.callbackContext = callbackContext;
		if ("doFileUploadApp".equals(action)) {
			if(!ActivityUtil.isNetworkAvailable(cordova.getActivity())){
				Toast.makeText(cordova.getActivity(), cordova.getActivity().getString(R.string.isNetworkAvailable), Toast.LENGTH_LONG).show();
				return false;
			}
			if(args == null || args.length() == 0){
				Toast.makeText(cordova.getActivity(), "请设置通讯参数", Toast.LENGTH_SHORT).show();
				return false;
			}
			try {
				url = args.optString(0);
				data = args.opt(1);
				type = args.optString(2);
                showConfirm = "false".equals(args.optString(3)) ? false : true;

				Intent intent = new Intent();
				intent.setClass(cordova.getActivity(), FileSelectorActivity.class);
				intent.putExtra(FileSelectorActivity.keyIsSelectFile,true);
				intent.putExtra(FileSelectorActivity.keyIsSingleSelector, false);
				intent.putExtra(FileSelectorActivity.keyFileTypes, type);
				cordova.startActivityForResult(FileUploadPlugins.this, intent, RETURNTYPE_FILEUPLOAD);
			} catch (Exception e) {
			}
			return true;
		}else if ("doInstantFileUploadApp".equals(action)) {
            if(!ActivityUtil.isNetworkAvailable(cordova.getActivity())){
                Toast.makeText(cordova.getActivity(), cordova.getActivity().getString(R.string.isNetworkAvailable), Toast.LENGTH_LONG).show();
                return false;
            }
            if(args == null || args.length() == 0){
                Toast.makeText(cordova.getActivity(), "请设置通讯参数", Toast.LENGTH_SHORT).show();
                return false;
            }
            try {
                url = args.optString(0);
                data = args.opt(1);
                Object _files = args.opt(2);
                if(_files instanceof String){
                    if (StringUtil.isNull(_files)) {
                        Message message = new Message();
                        message.what = 4;
                        message.obj = "请传人文件地址";
                        mHandler.sendMessage(message);
                        return true;
                    }
                    File f = new File((String) _files);
                    if (!f.exists()) {
                        Message message = new Message();
                        message.what = 4;
                        message.obj = "文件不存在";
                        mHandler.sendMessage(message);
                        return true;
                    }
                    if (!f.isFile()) {
                        Message message = new Message();
                        message.what = 4;
                        message.obj = "不是一个有效的文件";
                        mHandler.sendMessage(message);
                        return true;
                    }

                    List<String> list = new ArrayList<String>();
                    list.add((String) _files);
                    Message message = new Message();
                    message.what = 1;
                    message.obj = list;
                    mHandler.sendMessage(message);
                }else if(_files instanceof JSONArray) {
                    JSONArray files = (JSONArray) _files;
                    if (StringUtil.isNull(files) || files.length() == 0) {
                        Message message = new Message();
                        message.what = 4;
                        message.obj = "请传人文件地址";
                        mHandler.sendMessage(message);
                        return true;
                    }
                    for (int i = 0, j = files.length(); i < j; i++) {
                        String file = files.optString(i);
                        File f = new File(file);
                        if (!f.exists()) {
                            Message message = new Message();
                            message.what = 4;
                            message.obj = "文件不存在";
                            mHandler.sendMessage(message);
                            return true;
                        }
                        if (!f.isFile()) {
                            Message message = new Message();
                            message.what = 4;
                            message.obj = "不是一个有效的文件";
                            mHandler.sendMessage(message);
                            return true;
                        }
                    }

                    List<String> list = new ArrayList<String>();
                    for (int i = 0, j = files.length(); i < j; i++) {
                        list.add(files.optString(i));
                    }
                    Message message = new Message();
                    message.what = 1;
                    message.obj = list;
                    mHandler.sendMessage(message);
                }
            } catch (Exception e) {
            }
            return true;
        }
		return false;
	}
	
	public void onActivityResult(final int requestCode, final int resultCode, final Intent intent) {
		super.onActivityResult(requestCode, resultCode, intent);
		
		if (requestCode == RETURNTYPE_FILEUPLOAD && resultCode == Activity.RESULT_OK) {
            final ArrayList<String> list = intent.getStringArrayListExtra(FileSelectorActivity.keyFilePaths);

            if(showConfirm){
                ActivityUtil.showConfirmDialog(cordova.getActivity(), "立即上传选择的文件吗？", "确认", "取消", new ConfirmDialogListener() {
                    @Override
                    public void onOK() {
                        Message message = new Message();
                        message.what = 1;
                        message.obj = list;
                        mHandler.sendMessage(message);
                    }

                    @Override
                    public void onCancel() {//返回本地地址
                        Wait.sharedInstance().start(cordova.getActivity(), "正在处理图片...，请稍候");
                        cordova.getThreadPool().execute(new Runnable() {
                            @Override
                            public void run() {
                                com.alibaba.fastjson.JSONArray array = new com.alibaba.fastjson.JSONArray();
                                try{
                                    for(int i = 0, j = list.size(); i < j; i++){
                                        String path = list.get(i);

                                        path = PictureUtil.getFilePath(path);
                                        array.add(path);
                                    }
                                    Message message = new Message();
                                    message.what = 2;
                                    message.obj = array.toString();
                                    mHandler.sendMessage(message);
                                }catch (Exception e){
                                }finally {
                                    Wait.sharedInstance().stop();
                                }
                            }
                        });
                    }
                });
            }else{
                Message message = new Message();
                message.what = 1;
                message.obj = list;
                mHandler.sendMessage(message);
                /*
                Wait.sharedInstance().start(cordova.getActivity(), "正在处理图片...，请稍候");
                cordova.getThreadPool().execute(new Runnable() {
                    @Override
                    public void run() {
                        qs.openxt.libs.json.JSONArray array = new qs.openxt.libs.json.JSONArray();
                        try{
                            for(int i = 0, j = list.size(); i < j; i++){
                                String path = list.get(i);

                                path = PictureUtil.getFilePath(path);
                                array.put(path);
                            }
                            Message message = new Message();
                            message.what = 2;
                            message.obj = array.toString();
                            mHandler.sendMessage(message);
                        }catch (Exception e){
                        }finally {
                            Wait.sharedInstance().stop();
                        }
                    }
                });*/
            }
		}
	}
}
